package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	// Scrape query.
	threadQuery = `select  name,thread_desc, count(1) from v$threads group by name,thread_desc;`

	// Subsystem.
	threadPool = "thread_pool"
)

var (
	threadPoolDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, threadPool, "threads"),
		"The number of threads of each  type in the DM",
		[]string{"thread", "thread_desc"}, nil,
	)
)

type ThreadPool struct {
}

func (ThreadPool) Name() string {
	return "threadPool"
}
func (ThreadPool) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {

	var (
		name        string
		thread_desc string
		val         float64
	)
	threadPoolRows, err := db.Query(threadQuery)
	if err != nil {
		logger.Error("Failed to query thread pool", "error", err)
		return err
	}
	defer threadPoolRows.Close()
	for threadPoolRows.Next() {
		if err := threadPoolRows.Scan(&name, &thread_desc, &val); err != nil {
			logger.Error("Failed to scan thread pool row", "error", err)
			return err
		}
		ch <- prometheus.MustNewConstMetric(
			threadPoolDesc, prometheus.GaugeValue, val,
			name,
			thread_desc,
		)

	}

	return nil
}

func init() {
	RegisterScraper("threadPool", ThreadPool{})
}

var _ Scraper = ThreadPool{}
